﻿using System.ComponentModel;
using System.Windows;
using Samples.Radio.Helpers;

namespace Samples.Radio.Pages.Main
{
    public class PodcastTemplateSelector : DataTemplateSelector
    {
        public DataTemplate FirstItemTemplate { get; set; }
        public DataTemplate Template0 { get; set; }
        public DataTemplate Template1 { get; set; }
        public DataTemplate Template2 { get; set; }
        public DataTemplate Template3 { get; set; }


        private DataTemplate[] Templates
        {
            get
            {
                return new[]
                           {
                               Template0, Template1, Template2, Template3
                           };
            }
        }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (DesignerProperties.IsInDesignTool)
            {
                var isFirstProp = item.GetType().GetProperty("IsFirst");
                if (isFirstProp != null)
                {
                    var isFirst = (bool) isFirstProp.GetValue(item, null);
                    if (isFirst) return FirstItemTemplate;
                }

                var nameprop = item.GetType().GetProperty("ProgramName");
                if (nameprop != null)
                {
                    var name = nameprop.GetValue(item, null) as string;
                    var idx = name.Length%4;
                    return Templates[idx];
                }
            }

            var data = item as ProgramViewModel;
            if (data != null)
            {
                if (data.IsFirst) return FirstItemTemplate;

                var name = data.ProgramName;


                var idx = name.Length % 4;
                return Templates[idx];
            }
            return base.SelectTemplate(item, container);
        }
    }
}
